import { ESVisualObject } from "@sdkSrc/ESObjects";
import { Destroyable, ObjResettingWithEvent } from "xbsj-base";

export async function bindCustomEditing(sceneObject: ESVisualObject, updateEditing: () => void, bindEditingName: string = 'editing') {
    const bindCustomEditing = new Destroyable();
    sceneObject.ad(bindCustomEditing); // 自动删除
    let viewer = sceneObject.viewer
    if (!viewer) {
        await new Promise<void>((resolve) => {
            bindCustomEditing.ad(sceneObject.viewerChanged.don((e) => {
                viewer = e;
                resolve();
            }));
        });
    }
    if (!viewer) return;
    updateEditing();
    // @ts-ignore
    bindCustomEditing.ad(sceneObject[`${bindEditingName}Changed`].don(() => {
        //@ts-ignore
        if (sceneObject[`${bindEditingName}`]) {
            updateEditing();
        } else {
            viewer && viewer.stopEditing();
        }
    }));
    //@ts-ignore
    bindCustomEditing.ad(new ObjResettingWithEvent(sceneObject[`${bindEditingName}Changed`], () => {
        //@ts-ignore
        if (!sceneObject[`${bindEditingName}`] || !viewer) return undefined
        const updateEditingStatus = new Destroyable();
        updateEditingStatus.ad(viewer.editingEvent.don((e) => {
            if (e.type === 'end') {
                //@ts-ignore
                sceneObject[`${bindEditingName}`] = false;
            }
        }));
        return updateEditingStatus;
    }))
    return bindCustomEditing;
}